import React, { useEffect, useState } from "react";
import { Row, Col } from "antd";
import SearchTree from "@/biz-components/search-tree";
import AsyncTree from "@/biz-components/async-tree";
import { WithTreeListProps } from "hoc-form";
import { withRouter } from 'umi';
import NodeText from "@/biz-components/node-text";
import { useListComp } from "./use-hooks";
const WithTreeList: React.FC<WithTreeListProps & {refreshFlag: boolean; selectNode: (node: any) => void;}> = (props) => {
  const nodeRef = React.useRef();
  const WithListComp = useListComp();
  const {
    metasConfig,
    modalMetasConfig,
    outerNode,
    keyName,
    titleName,
    cantUnSelect = false,
    defaultSelectedKeys,
    defaultExpandedKeys,
    modalfiledConfig,
    modalformConfigs,
    modalCode,
    paramsMap = [],
    noModal,
    url,
    urlTable,
    match,
    method = "GET",
    events,
    treeParams,
    handleSave,
    extraPrams = {},
    validator,
    nodeKeys = ["code"],
    pageApi,
    searchCode,
    async = false,
    noQueryKeys = false,
    history,
    nodeSelect,
    rowSelection,
    rowKey,
    onCancel,
    nodeButtons = null,
    api,
    refreshFlag = false,
    selectNode
  } = props;
  const [treeNode, setTreeNode] = useState<any>(async ? { isRoot: true } : {});
  const [changeTree, setChangeTree] = useState<any>();
  const [refreshTree, setRefreshTree] = useState(0);
  const [refresh, setRefresh] = useState(false);

  console.log("redloading", urlTable, extraPrams);
  const initParamsMap = {};
  paramsMap.forEach((key, index) => {
    initParamsMap[key] = null;
  });

  const [tableParams, settableParams] = useState<any>({
    ...initParamsMap,
    ...extraPrams,
  });
  useEffect(() => {
    console.log("tableParams3", {
      ...tableParams,
      ...extraPrams,
    });
    settableParams({
      ...tableParams,
      ...extraPrams,
    });
  }, [JSON.stringify(extraPrams)]);
  useEffect(() => {
    setRefresh(refresh + 1);
    setRefreshTree(refreshTree + 1);
  }, [refreshFlag])
  console.log("tableParams", tableParams);
  const handleSelectNode = (node: any) => {
    console.log("handleSelectNode------>", node);
    if (nodeSelect) nodeSelect(node);
    if (!node) {
      settableParams({ ...initParamsMap, ...extraPrams });
      return;
    }
    setTreeNode(node);
    selectNode?.(node);
    nodeRef.current = node;
    const params = {};
    if (paramsMap && paramsMap.length > 0 && node) {
      paramsMap.forEach((key, index) => {
        params[key] = node[nodeKeys[index]] || null;
      });
    }
    settableParams({
      ...params,
      ...extraPrams,
      parentCode: node[keyName]
    });
    setRefresh(refresh + 1);
  };
  const changeTreeData = () => {
    setChangeTree(!changeTree);
  };

  const map = {
    effects() {
      if (modalformConfigs) {
        modalformConfigs({
          treeNode: nodeRef,
        });
      }
    },
  };
  console.log("hoc-render");
  return (
    <Row>
      <Col span={6} className="leftTree tree">
        {!async ? (
          <SearchTree
            refreshFlag={refreshTree}
            onSelect={handleSelectNode}
            canSearch
            outerNode={outerNode}
            keyName={keyName}
            titleName={titleName}
            cantUnSelect={cantUnSelect}
            defaultSelectedKeys={defaultSelectedKeys}
            defaultExpandedKeys={defaultExpandedKeys}
            api={{
              type: method,
              url,
              params: method === "POST" ? { ...treeParams } : {},
            }}
          />
        ) : (
          <AsyncTree
            method={method}
            url={url}
            nodeInfo={treeNode}
            treeNodeClick={handleSelectNode}
            changeTree={changeTree}
            changeTreeData={changeTreeData}
          />
        )}
      </Col>
      <Col span={16}>
        {/* {}{ treeNode.code ? nodeButtons : null} */}
        {treeNode ? (
          <NodeText
            buttons={nodeButtons}
            text={
              treeNode?.code
                ? `当前节点:${treeNode?.name || ""}-${treeNode?.code || ""}`
                : ""
            }
          />
        ) : (
          ""
        )}
        {WithListComp.current && (
          <WithListComp.current
            match={match}
            handleSave={handleSave}
            onCancel={onCancel}
            rowKey={rowKey}
            rowSelection={rowSelection}
            modalfiledConfig={modalfiledConfig}
            modalformConfigs={map}
            noModal={noModal}
            history={history}
            validator={validator}
            // reloadFlag={urlTable}
            reloadFlag={refresh}
            modalCode={modalCode}
            events={events}
            noQueryKeys={noQueryKeys}
            extraPrams={tableParams}
            pageApi={pageApi}
            metasConfig={metasConfig}
            modalMetasConfig={modalMetasConfig}
            api={api}
            pageCode={searchCode}
          />
        )}
      </Col>
    </Row>
  );
};

// @ts-ignore
export default withRouter<WithTreeListProps>(WithTreeList);
